package com.situ.crm.filter;

import com.situ.crm.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

// /*代表拦截所有的请求
//@WebFilter(filterName = "login", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8");

        //1、对于获得js、css、png不需要判断是否登录
        //2、对于要完成登录的操作也不需要判断是否登录
        // /user?method=login   /user?method=add
        String servletPath = request.getServletPath();
        System.out.println("servletPath: " + servletPath);
        String method = request.getParameter("method");

        if (servletPath.endsWith(".jpg")
            || servletPath.endsWith(".png")
            || servletPath.endsWith(".js")
            || servletPath.endsWith(".css")
            || servletPath.equals("/login.jsp")
            || servletPath.equals("/checkImage")
            || servletPath.equals("/user") && "login".equals(method)) {
            //方行，直接访问后面资源
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {//用户没有登录过
            response.sendRedirect("/login.jsp");
            return;
        }

        //代表已经登录，方行访问后面的资源
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
